package shiqi.convert;

import java.lang.reflect.Field;

/**
 * @program: ascend
 * @description: 转换类
 * @author: shiqi
 * @create: 2022-03-17 19:55
 **/
public class ConvertUtil {

    /**
     * @param
     * @return void
     * @author shiqi
     * @createTime 2022/3/17 19:57
     * @desc 将source的同名属性的值复制到target,利用反射
     */
    public static void convert(Object target, Object source) {
        try {
            Class<?> targetClass = target.getClass();
            Class<?> sourceClass = source.getClass();
            Field[] sourceClassDeclaredFields = sourceClass.getDeclaredFields();
            for (Field field : sourceClassDeclaredFields) {
                String name = field.getName();
                System.out.println(name);
                Field targetField = targetClass.getDeclaredField(name);
                if (targetField != null) {
                    if (!field.isAccessible()) {
                        field.setAccessible(true);
                    }
                    if (!targetField.isAccessible()) {
                        targetField.setAccessible(true);
                    }
                    targetField.set(target, field.get(source));
                }

            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
